#include "Http_Lib.h"


CRITICAL_SECTION CriticalSection;
HANDLE hGlobalWaitEvent;
int already_write_size;
int file_size;
range h_range;


void __stdcall ThreadProc(void* lp)
{
	HttpGet(lp);
}


int HttpDownload(char* server_name, int port, char* fullpathname, int thread_num, char* storepathname)
{
	PMYDATA pData[MAX_THREAD_NUM];
	HANDLE hThread[MAX_THREAD_NUM];	
	int i, temp;

	InitializeCriticalSection(&CriticalSection);

	pData[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(MYDATA));
	pData[0]->server_name = server_name;
	pData[0]->port = port?port:DEFAULT_PORT;
	pData[0]->fullpathname = fullpathname;
	pData[0]->h_index = 0;
	pData[0]->storepathname = storepathname;

	hGlobalWaitEvent = CreateEvent(NULL,TRUE,FALSE,"WriteEvent");
	if(hGlobalWaitEvent == NULL)
    { 
        printf("CreateEvent failed (%d)\n", GetLastError());
        goto exit;
    }
	ResetEvent(hGlobalWaitEvent);

	h_range.start[0] = 0;
	hThread[0] = CreateThread(NULL,0,ThreadProc,pData[0],0,NULL);

	WaitForSingleObject(hGlobalWaitEvent, INFINITE);
	EnterCriticalSection(&CriticalSection);
	temp = file_size - already_write_size;
	temp/= thread_num;
	already_write_size+=temp;
	h_range.end[0] = already_write_size;

	for(i=1;i<thread_num;i++)
	{
		h_range.start[i] = h_range.end[i-1];
		h_range.end[i] = h_range.start[i] + temp;
		pData[i] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(MYDATA));
		pData[i]->fullpathname = fullpathname;
		pData[i]->server_name = server_name;
		pData[i]->h_index = i;
		pData[i]->port = port?port:DEFAULT_PORT;
		pData[i]->storepathname = storepathname;
		hThread[i] = CreateThread(NULL,0,ThreadProc,pData[i],0,NULL);
	}
	LeaveCriticalSection(&CriticalSection);
	WaitForMultipleObjects(thread_num,hThread,TRUE,INFINITE);
exit:
	CloseHandle(hGlobalWaitEvent);
	DeleteCriticalSection(&CriticalSection);
	return 0;
}

int main()
{
	HttpDownload("timxu.net9.org",80,"/d.exe",10,"D:\\");
	return 0;
}